﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Linq;
using System.Web.Mvc;

namespace BGCMS.Models
{
    /// <summary>
    /// A partial model class used for integrating validation and business rule logic
    /// </summary>
    public partial class Article
    {
        /// <summary>
        /// Indicates whether the Article object has any active RuleViolations
        /// </summary>
        public bool IsValid
        {
            get
            {
                return (ArticleGetRuleViolations().Count() == 0); 
            }
        }

        /// <summary>
        /// Causes our validation and business rules to be evaluated.
        /// </summary>
        /// <returns>Returns a sequence of ArticleRuleViolation objects that provide more 
        /// details about any rule errors.</returns>
        public IEnumerable<ArticleRuleViolation> ArticleGetRuleViolations()
        {
            if(String.IsNullOrEmpty(Title))
                yield return new ArticleRuleViolation("Hver er titill greinarinnar?", "Title");

            if (String.IsNullOrEmpty(TextBody))
                yield return new ArticleRuleViolation("Hvert er innihald greinarinnar","TextBody");

            yield break;
        }
    }

    /// <summary>
    /// A helper class that provides more details about a rule violation
    /// </summary>
    public class ArticleRuleViolation
    {
        public string ArticleErrorMessage { get; private set; }
        public string ArticlePropertyName{ get; private set; }

        public ArticleRuleViolation(string errorMessage, string propertyName)
        {
            ArticleErrorMessage = errorMessage;
            ArticlePropertyName = propertyName;
        }
    }

    public static class ControllerHelpers
    {
        public static void ArticleAddRuleViolations(this ModelStateDictionary modelState, IEnumerable<ArticleRuleViolation> errors)
        {
            foreach (ArticleRuleViolation issue in errors)
            {
                modelState.AddModelError(issue.ArticlePropertyName, issue.ArticleErrorMessage);
            }
        }
    }
}